const bcrypt = require('bcryptjs');
const UserModel = require('../../db/models/user');

// 获取菜单列表 (按条件查询)
const queryUserList = async function (ctx, next) {
  let params = ctx.request.query;
  let reg = new RegExp(params.username, 'i');
  let userList = await UserModel.find({
    $or: [{ username: { $regex: reg } }]
  }).select('username role');
  ctx.body = userList;
}

// 增加用户
const addUser = async function (ctx, next) {
  let data = ctx.request.body;
  data.password = bcrypt.hashSync(data.password, 10);
  await UserModel.create(data).then(() => {
    ctx.body = {
      success: true
    }
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    }
  })
}

// 删除用户
const deleteUser = async function (ctx, next) {
  let params = ctx.request.query;
  await UserModel
    .deleteMany({ _id: { $in: params._id.split(',') }})
    .then(() => {
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    })
}

// 更新用户信息
const updateUser = async function (ctx, next) {
  let data = ctx.request.body;
  await UserModel
    .where({ _id: data._id })
    .update(data)
    .then(() => {
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    })
}

// 查询单个用户信息
const queryOneUser = async function (ctx, next) {
  let params = ctx.request.query;
  await UserModel.find(params).then(res => {
    ctx.body = {
      success: true,
      data: res
    }
  }).catch(err => {
    ctx.body = {
      success: false,
      msg: err.message
    }
  })
}

// 修改用户密码
const updateUserPwd = async function (ctx, next) {
  let data = ctx.request.query;
  let paylod = ctx.state.user;
  let userInfo = await UserModel.findOne({ _id: paylod._id });
  if (!bcrypt.compareSync(data.oldPwd, userInfo.password)) {
    ctx.body = {
      success: false,
      msg: '原密码不正确！'
    }
    return false;
  }
  let newPwd = bcrypt.hashSync(data.newPwd, 10);
  await UserModel
    .where({ _id: paylod._id })
    .update({ password: newPwd })
    .then(() => {
      ctx.body = {
        success: true
      }
    })
    .catch(err => {
      ctx.body = {
        success: false,
        msg: err.message
      }
    })
}

module.exports = {
  queryUserList,
  addUser,
  deleteUser,
  updateUser,
  queryOneUser,
  updateUserPwd
}